<?php
/*=============================================================================
|| ##################################################################
||	phpFoX Konsort
|| ##################################################################
||
||	Copyright		: (C) 2005-2007 PHPFOX Limited a Reality Fox Creation
||	Contact			: info@phpfox.com
||
||	- phpFoX and all of its source code and files are protected by Copyright Laws.
||
||	- The license for phpFoX permits you to install this software on a single domain (.com, .org, .net, etc.).
||
||	- You may also not remove this copyright screen which shows the copyright information and credits for phpFoX (RealityFOX Creations).
||
||	- phpFoX Konsort is NOT a FREE software - http://www.phpfox.com/license/
||
|| ##################################################################
=============================================================================*/

/* $File: ./include/modules/Gallery/classes/PhpFox_ComponentView.class.php, $Author:  $ */

/** Component for viewing gallery items
 *
 * @version $Id: PhpFox_ComponentView.class.php 469 2008-06-11 21:12:06Z phpfoxsv $
 * @package module.gallery
 */
class PhpFox_Mod_Gallery_ComponentView extends BaseComponent
{
    function process()
    {
        $oGalleryItem = $this->_oModule->getItem('Gallery');
        /* @var $oGalleryItem PhpFox_Mod_Gallery_ItemGallery */
        $oGalleryService = $this->_oModule->getService('Gallery');
        /* @var $oGalleryService PhpFox_Mod_Gallery_ServiceGallery */
        $oSecurityService = App::getModuleService('Account', 'Security');
        /* @var $oSecurityService PhpFox_Mod_Account_ServiceSecurity */
        App::loadClass('Filter');
        $oReq = &App::getRequest();
        $oUrl = &App::getUrl();
        $oTpl = $this->_oModule->getTemplate();
        $aOut = array();

        $oSecurityService->checkPerm('gallery', array('read_only', 'full'));
        $oSecurityService->checkAccess('gallery');

        if (!$iId = $oReq->getInt('id'))
        {
            App::gotoUrl('public.gallery.main');
        }

        if ($iItemId = $oReq->getInt('makefeature'))
        {
        	if (App::isStaff())
            {
            	$oGalleryItem->load($iItemId);
            	$oGalleryItem->aData['feature'] = 1;            	
            	$oGalleryItem->update(array('feature'));
            }
            $oUrl->clearParams('makefeature');
            App::forward($oUrl->getUrl());
        }
        if ($iItemId = $oReq->getInt('removefeature'))
        {
            if (App::isStaff())
            {
	            $oGalleryItem->load($iItemId);
	            $oGalleryItem->aData['feature'] = '';
	            $oGalleryItem->update(array('feature'));
            }
            $oUrl->clearParams('removefeature');
            App::forward($oUrl->getUrl());
        }             
        
        $aCategories = array();
        $aCategories[''] = App::format('option.select');
        foreach (App::getOptions('image_cat') as $sCategoryId => $sCategoryText)
        {
            $aCategories[$sCategoryId] = $sCategoryText;
        }
        $aFields = array
        (
            'category' => array
            (
                'select' => $aCategories,
                'value'  => '=',
            ),
        );
        $oFilter = &new Filter('galbrowse', $aFields);
        $aCond = array();
        $aCond[] = 'g.allow = ""';
        $aCond[] = 'g.who_view = ""';
        foreach ($oFilter->aConditions as $sCond)
        {
        	$sCond = preg_replace('#{\#(.*)}#i', ' g.\\1', $sCond);
            $aCond[] = $sCond;
        }
        $sSort = $oReq->get('field', 'time');
        $aSortFields = array
        (
            'time',
            'rating',
            'view',
        );
        if (!in_array($sSort, $aSortFields))
        {
            $sSort = 'time';
        }

		$sConditions = "";
		if ( isset($aCond) && count($aCond) > 0 )
		{
        	$sConditions = " AND " . implode(" AND ", $aCond);
        }

        $oLang =& App::getLanguage();
        
        $aData = $this->oDatabase->getRow('
        	SELECT 
        		g.id, g.user_id, g.allow, g.who_view, g.view, g.time, g.text, g.rating, g.comment, g.feature, u.user, l.text AS cname
        	FROM '. App::getT('main') .' AS g
        		JOIN '. App::getT('user') .' AS u ON(g.user_id = u.id)
        		LEFT JOIN '	. App::getT('language_options') . ' AS l ON(l.languageid = "' . $oLang->aLanguage['id'] .'" AND l.varid = g.category AND l.varname = "image_cat")
        	WHERE g.id = "'. $iId .'" '. $sConditions .'
        ');

        if (!isset($aData['id']))
        {
            App::gotoUrl('public.gallery.main');
        }

		if (CAN_SET_COOKIE && $this->_oModule->getSessVar("viewed_". $aData['id'] ."") != 'natio')
		{
        	$aData['view']++;
        	$this->oDatabase->query("UPDATE ". App::getT('main') ." SET view = '". $aData['view'] ."' WHERE id = '". $iId ."'");
        	$this->_oModule->setSessVar("viewed_". $aData['id'] ."", "natio");
        }

        $sImagePath = App::getParam('gallery.pic.path').$aData['id'].'.jpg';
        
        list($iWidth, $iHeight) = $oGalleryService->getImageResolution($sImagePath);

        $iNextId = 0;
        switch ($sSort)
        {
            case 'time':
                $aArr = 'g.time < '.$aData['time'];
                $sSqlSort = 'time DESC';
                break;
            case 'rating':
                $aArr = 'g.rating < '.$aData['rating'];
                $sSqlSort = 'rating DESC';
                break;
            case 'view':
                $aArr = 'g.view < '.$aData['view'];
                $sSqlSort = 'view DESC';
                break;
        }
		$aItems = $this->oDatabase->getRow("SELECT g.id FROM ". App::getT('main') ." AS g ".
			"WHERE ".
			$aArr .
			$sConditions .
			" ORDER BY $sSqlSort LIMIT 0,1 ");
		if ( isset($aItems['id']) )
		{
			$iNextId = $aItems['id'];
		}

        $iPrevId = 0;
        switch ($sSort)
        {
            case 'time':
                $aArr = 'g.time > '.$aData['time'];
                $sSqlSort = 'time ASC';
                break;
            case 'rating':
                $aArr = 'g.rating > '.$aData['rating'];
                $sSqlSort = 'rating ASC';
                break;
            case 'view':
                $aArr = 'g.view > '.$aData['view'];
                $sSqlSort = 'view ASC';
                break;
        }
		$aItems = $this->oDatabase->getRow("SELECT g.id FROM ". App::getT('main') ." AS g ".
			"WHERE ".
			$aArr .
			$sConditions .
			" ORDER BY $sSqlSort LIMIT 0,1 ");
		if ( isset($aItems['id']) )
		{
			$iPrevId = $aItems['id'];
		}
		
		$sActualImage = App::getParam('gallery.pic.url') . $aData['id'] . '_view.jpg';
		if (!file_exists(App::getParam('gallery.pic.path') . $aData['id'] . '_view.jpg'))
		{
			$sActualImage = App::getParam('gallery.pic.url') . $aData['id'] . '.jpg';
		}

		if (App::getParam('bImageSecurity'))
		{
			App::setAccessForContent('gallery', $aData['id']);
		}
		
        $oTpl->assign(array(
        	'sActualImage' => $sActualImage,
        	'iImgViewSize' 		=> App::getParam('upload_set_size_view'),
        	'bUseLightbox' => App::getParam('use_lightbox'),
            'aItem'            => $aData,
            'iWidth'           => $iWidth,
            'iHeight'          => $iHeight,
            'bLoggedIn'        => ($oSecurityService->getCurrentUserLogin()) ? true : false,
            'iNextId'          => $iNextId,
        	'aFilter'          => $oFilter->aHtml,
        	'sFilterName'      => 'galbrowse',
        	'sFilterUrl'       => App::makeUrl('public.gallery.main'),
            'iFileSize'        => $oGalleryService->getImageSize($sImagePath),
            'iPrevId'          => $iPrevId,
            'bCanRate'         => $oSecurityService->checkAccess('rate', '', false),
            'sMonthDateFormat' => App::getParam('format.monthdate%'),
            'sGImageUrl'       => App::getParam('gallery.pic.url'),
            'sUImageUrl'       => App::getParam('user.pic.url'),
            'sField'	=> $oReq->get('field'),
            'sEnlargeImage' => App::format('Mod_Gallery.click_to_enlarge_image')
        ));
        $aOut['main'] = $oTpl->fetch('View.html');
        $aOut['filter'] = $oTpl->fetch('GroupFilter.html');
        return $aOut;
    }
}
?>